package com.bds.tjj.task;

import java.util.Date;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.StringUtils;

import com.bds.tjj.http.HttpBase;
import com.bds.tjj.model.News;
import com.bds.tjj.service.NewsService;
import com.bds.tjj.utils.SpringContextUtil;

public class NewsThread extends Thread {
	private static final Logger logger = Logger.getLogger(NewsThread.class);

	public NewsThread() {

	}

	@Override
	public void run() {
		NewsService newsService = SpringContextUtil.getBean("newsService", NewsService.class);
		String url = "http://www.stats.gov.cn/tjsj/zxfb/index.html";

		HttpBase http = new HttpBase();
		String first = "http://www.stats.gov.cn/tjsj/zxfb";
		try {
			String html = http.get(url, "utf-8", null);
			if (!StringUtils.isEmpty(html)) {
				Document doc = Jsoup.parse(html);
				Elements es = doc.select("ul.center_list_contlist li:not(.cont_line)");
				for (Element e : es) {
					String link = "";
					Element a = e.select("a").first();
					String href = a.attr("href");
					String title = e.select("a span font.cont_tit03").text();
					String pub_date = e.select("a span font.cont_tit02").text();
					if (href.startsWith(".")) {
						link = first + href.substring(1, href.length());
					} else {
						link = "http://www.stats.gov.cn" + href;
					}
					News news = new News();

					news.setContent(title);
					news.setLink(link);
					news.setPubdate(pub_date);
					news.setTitle(title);
					news.setCreate_time(new Date());
					newsService.saveNews(news);
					logger.info(href);
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
